<template>
    <div class="allocation">
        <van-nav-bar title="更换货架" left-arrow @click-left="handleLeft">
        </van-nav-bar>
        <div class="flexd">
            <div @click="selectOneProduct()" class="addArehousing_item">
                <div class="imgs"><van-image :src="add"></van-image></div>
                <div class="title">选择商品</div>
            </div>
            <div @click="saomaClick" class="addArehousing_item addArehousing_code">
                <div class="imgs"><van-image :src="saoma"></van-image></div>
                <div class="title">扫码调拨</div>
            </div>
        </div>
        <div class="titles">
            商品明细
            <span v-if="allocationName == '货架'">当前货架：{{ shelvesCode }}</span>
        </div>
        <div class="conent">
            <div v-for="(item, index) in warehouseList" :key="index" class="conent_pre">
                <div class="conent_pre_header">
                    <div class="conent_pre_img">
                        <van-image :src="item.productImage + '?x-oss-process=image/resize,w_300'"
                            v-if="item.productImage" @click="enlargeImage(item.productImage)">
                            <div class="liveStreamingMechanisms" v-if="item.hmMechanismsList[1]?.cooperationMode">多机制
                            </div>
                        </van-image>
                        <van-image :src="errImg" v-else>
                            <div class="liveStreamingMechanisms" v-if="item.hmMechanismsList[1]?.cooperationMode">多机制
                            </div>
                        </van-image>
                    </div>
                    <div class="conent_pre_des">
                        <div class="contnt_title">
                            <div class="contnt_styleName">
                                {{ item.styleName }}
                            </div>
                            <div :class="'contnt_status' + item.shelvesStatus">
                                {{ shelvesStatusNameByIdss(item.shelvesStatus) }}
                            </div>
                        </div>
                        <div class="contnt_mechanism">
                            {{ item.sellingPoints }}
                        </div>
                        <div class="contnt_bottom">
                            <div class="price">￥ {{
                                item.hmMechanismsList[0]?.price || item.hmMechanismsList[0]?.costPrice }}</div>
                            <div class="commission" v-if="item.hmMechanismsList[0]?.commission">佣 {{
                                (item.hmMechanismsList[0]?.commission || 0) + "%"
                            }}</div>
                            <div class="coreName">{{ item.coreName }}</div>
                        </div>
                    </div>
                </div>
                <div class="product_detail_title--content">
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">机制：</div>
                        <div class="product_detail_title-content-info-content">
                            {{ item.hmMechanismsList[0]?.liveStreamingMechanism }}
                        </div>
                    </div>
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">规格/材质：</div>
                        <div class="product_detail_title-content-info-content">
                            {{ item.specs }}
                        </div>
                    </div>
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">当前库存：</div>
                        <div class="product_detail_title-content-info-content colors">
                            {{ item.stockAvailable }}件
                        </div>
                    </div>
                    <div class="product_detail_title-content-info">
                        <div class="product_detail_title-content-info-name">库存编码：</div>
                        <div class="product_detail_title-content-info-content">
                            {{ item.stockCode }}
                        </div>
                    </div>
                    <div class="product_detail_title-content-info" v-if="allocationName == '商品'">
                        <div class="product_detail_title-content-info-name">当前货架：</div>
                        <div class="product_detail_title-content-info-content colors">
                            {{ item.locationName }}
                        </div>
                    </div>
                    <div class="divs">
                        <div class="buttons" @click="removeClick(item)">移除</div>
                    </div>
                </div>
            </div>
        </div>
        <div class="conputed_bottom">
            <div class="conputed_bottom_left">
                <van-field label="绑定新货架号" v-model="goodsShelves" placeholder="请输入" required>
                    <template #right-icon>
                        <img class="icons" :src="saoyisao" alt="" @click="replaceShelves">
                    </template>
                </van-field>
            </div>
            <div class="button" @click="submit">确定</div>
        </div>
        <van-overlay :show="overlayShow">
            <van-loading color="#1989fa">加载中...</van-loading>
        </van-overlay>
        <van-dialog v-model:show="dialogShow" title="提示" :showConfirmButton="false">
            <div class="dialog_title">{{
                allocationName == '货架' ?
                    '确认' + shelvesCode + '货架上的全部商品更换到' + goodsShelves :
                    computedTitles
            }}</div>
            <div class="dialog_buttons">
                <div @click="cancel" class="cancel">取消</div>
                <div @click="warehousingClick" class="save" v-throttle:click>确认</div>
            </div>
        </van-dialog>
    </div>
</template>

<script setup lang="ts">
import { showConfirmDialog, showFailToast, showImagePreview, showSuccessToast } from 'vant';
import { ref, onMounted, computed, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { shelvesStatusNameByIdss } from '@/utils/statusNameById'
import { getEnvValue } from "@/utils/index";
import { stockLocation, scanGoodsShelves, selectGrounding, addAllocate } from '@/api/productHome/index'
const router = useRouter();
const route = useRoute();
const errImg = new URL("@/assets/home/error.png", import.meta.url).href;
const saoyisao = new URL("@/assets/productHome/icon_saoyisao1.png", import.meta.url).href;
const add = new URL("@/assets/productHome/icon_tianjia.png", import.meta.url).href;
const saoma = new URL("@/assets/productHome/icon_saoyisao1.png", import.meta.url).href;
const overlayShow = ref(false)

const warehouseList = ref<any>([])
// 商品id集合
const warehouseListId = ref<any>([])
// 扫码类型 货架or商品
const allocationName = ref<any>('')
// 更换货架号
const goodsShelves = ref()
// 当前货架号
const shelvesCode = ref()
// 二次确认弹窗
const dialogShow = ref(false)

// 商品选择传输数据
const info = computed(() => {
    return route.query.info;
})


/** 选择商品时候 */
watch(
    () => info.value,
    (v: any) => {
        // 选择调拨商品时
        allocationName.value = localStorage.getItem('allocationName') || undefined
        if (v) {
            if (localStorage.getItem('allocateList')) {
                allocationName.value = '商品'
                warehouseList.value = JSON.parse(localStorage.getItem('allocateList') as any)
                const date = JSON.parse(v)
                warehouseList.value.push(...date)
            } else {
                const date = JSON.parse(v)
                warehouseList.value.push(...date)
            }
        } else {
            warehouseList.value = JSON.parse(localStorage.getItem('allocateList') as any) || []
        }
        warehouseListId.value = JSON.parse(localStorage.getItem('allocateIdList') as any) || []
        goodsShelves.value = localStorage.getItem('allocateShelves') || undefined
    },
    { immediate: true }
)
/** 选择商品 */
const selectOneProduct = () => {
    localStorage.setItem("allocateList", JSON.stringify(warehouseList.value));
    localStorage.setItem("allocateIdList", JSON.stringify(warehouseListId.value));
    localStorage.setItem("allocationName", allocationName.value);
    goodsShelves.value && localStorage.setItem("allocateShelves", goodsShelves.value);
    router.push({
        path: '/transferProductList'
    })
}
/** 清空缓存 */
const removeLocalStorage = () => {
    localStorage.removeItem("allocateList");
    localStorage.removeItem("allocateIdList");
    localStorage.removeItem("allocateShelves");
    localStorage.removeItem("allocationName");
}
/** 回退 */
const handleLeft = () => {
    if (warehouseList.value.length) {
        showConfirmDialog({
            message:
                '退出后将不保留未完成操作',
        })
            .then(() => {
                router.push('/inventoryAllocation')
                removeLocalStorage()
            })
            .catch(() => {
                // on cancel
            });
    } else {
        router.push('/inventoryAllocation')
        removeLocalStorage()
    }

}
/** 新增商品扫码 */
const saomaClick = () => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "scanCode",
            name: "allocation"
        },
    })
}
/** 绑定新货架号 */
const replaceShelves = () => {
    (window as any).uni.webView.postMessage({
        data: {
            type: "scanCode",
            name: "replaceShelves"
        },
    })
}
/** 移除当前数据 */
const removeClick = (item: any) => {
    const removeIndex = warehouseList.value.indexOf(item)
    // 删除其中数据
    warehouseList.value.splice(removeIndex, 1)
    warehouseListId.value.splice(removeIndex, 1)
}
/** 调拨商品 判断全部商品调拨还是部分商品 */
const computedTitles = computed(() => {
    // 部分商品
    const indexs = warehouseList.value.indexOf(item => item.locationName == goodsShelves.value)
    if (indexs !== -1) {
        return '部分商品已在当前货架，其余选中商品将更换到' + goodsShelves.value
    } else {
        return '选中商品将全部更换到' + goodsShelves.value
    }
});
/** uniapp端回传扫码数据 */
(window as any).msgFromUniapp = async (arg) => {
    // 调拨选择商品
    if (arg.name == 'allocation') {
        overlayShow.value = true
        try {
            // 货架扫码 新增整个货架商品
            if (arg.productId.indexOf('-') != -1) {
                if (allocationName.value == '商品') {
                    showFailToast('请选择商品码扫码')
                } else {
                    if (typeof arg.productId === 'string') {
                        await stockLocation({ name: arg.productId })
                        shelvesCode.value = arg.productId
                        // L8-1-1-1货架上数据过多 导致得接口出现当即问题
                        if (arg.productId == 'L8-1-1-1') {
                            showFailToast({ message: '当前货架暂时无法调拨' });
                        } else {
                            const res = await scanGoodsShelves({ shelvesCode: arg.productId })
                            if (res.rows.length > 0) {
                                res.rows.forEach(element => {
                                    if (element.productImage) {
                                        element.productImage = getEnvValue("VITE_APP_PIC_URL") + element.productImage.split(',')[0]
                                    }
                                });
                                warehouseList.value = res.rows
                                warehouseListId.value = res.rows.map(item => item.id)
                                allocationName.value = '货架'
                            } else {
                                showFailToast({ message: '该货架上暂无商品' });
                            }
                        }
                    } else {
                        showFailToast({ message: '货架码错误' });
                    }
                }
            } else {
                allocationName.value = '商品'
                const res = await selectGrounding({ productsId: arg.productId });
                res.rows[0].productImage = getEnvValue("VITE_APP_PIC_URL") + res.rows[0].productImage.split(',')[0]
                if (warehouseList.value.filter((item) => item.id == res.rows[0].id).length == 0) {
                    warehouseList.value.push(res.rows[0])
                    warehouseListId.value.push(res.rows[0].id)
                } else {
                    showFailToast('该商品已存在')
                }
            }
            overlayShow.value = false
        } catch (error) {
            overlayShow.value = false
        }

        // 换库位码
    } else if (arg.name == 'replaceShelves') {
        if (typeof arg.productId === 'string') {
            await stockLocation({ name: arg.productId })
            goodsShelves.value = arg.productId
        } else {
            showFailToast({ message: '货架码错误' });
        }
    }
}
/** 图片放大 */
const enlargeImage = (img: string) => {
    if (img) {
        showImagePreview({
            images: [img],
        });
    }
};
/** 提交交换货架 */
const submit = async () => {
    if (warehouseList.value.length == 0) {
        showFailToast({ message: '请选择商品' });
    } else {
        // 验证货架是否合法
        await stockLocation({ name: goodsShelves.value })
        if (allocationName.value == '货架') {
            if (goodsShelves.value == shelvesCode.value) {
                showFailToast({ message: '调拨货架号与调拨前一致，无法调拨，请检查货架号！' });
            } else {
                dialogShow.value = true
            }
        } else {
            if (warehouseList.value.filter(item => item.locationName == goodsShelves.value).length == warehouseList.value.length) {
                showFailToast({ message: '全部商品已在当前货架，无法调拨，请检查货架号！' });
            } else {
                dialogShow.value = true
            }
        }
    }
}
/** 二次确认提交 */
const warehousingClick = async () => {
    const boList = warehouseList.value.map((item: any) => {
        return {
            productsId: item.id,
            stockCode: item.stockCode,
            locationId: item.locationId,
            locationCode: item.locationName,
            styleName: item.styleName
        }
    })
    await addAllocate({
        // 新的货架号
        locationCode: goodsShelves.value,
        boList
    })
    showSuccessToast('更换货架成功')
    setTimeout(() => {
        removeLocalStorage()
        allocationName.value = ''
        router.push('/transferSuccessful')
    }, 500);
}
/** 二次取消 */
const cancel = () => {
    dialogShow.value = false
}
onMounted(() => {
    // (window as any).uni.webView.postMessage({
    //     data: {
    //         type: "scanCode",
    //         name: "allocation"
    //     },
    // })
})


</script>
<style lang="less" scoped>
.allocation {
    height: calc(100vh - 44px);
    width: 100%;
    background: #F6FAFF;
    box-sizing: border-box;
    overflow: hidden;

    .menu_cion {
        width: 19px;
        height: 18px;
    }

    .flexd {
        display: flex;
        align-items: center;

        .addArehousing_item {
            width: 151px;
            height: 42px;
            background: #FFFFFF;
            border-radius: 21px;
            font-weight: 400;
            font-size: 16px;
            color: #0094FF;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: auto;
            margin-top: 15px;

            .imgs {
                width: 25%;
                height: 100%;
                display: flex;
                align-items: center;
                justify-content: right;
            }

            .title {
                width: 70%;
                display: flex;
                align-items: center;
                padding-left: 10px;
                box-sizing: border-box;
            }

            .van-image {
                width: 16px;
                height: 16px;
            }
        }

        .addArehousing_code {
            margin-top: 15px !important;
        }
    }

    .titles {
        font-weight: 500;
        font-size: 16px;
        color: #1A1B1C;
        margin: 15px 15px 5px 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        span {
            font-size: 14px;
            color: #009DFF;
        }
    }

    .conent {
        height: calc(100% - 148px);
        width: 100%;
        overflow: auto;
        padding-bottom: 120px;
        box-sizing: border-box;
    }

    .conputed_bottom {
        width: 375px;
        height: 120px;
        background: #FFFFFF;
        box-shadow: 0px 0px 8px 0px rgba(189, 195, 204, 0.5);
        box-sizing: border-box;
        padding: 15px;
        position: fixed;
        bottom: 0;

        .button {
            width: 345px;
            height: 44px;
            background: #0094FF;
            border-radius: 23px;
            text-align: center;
            line-height: 44px;
            font-weight: 400;
            font-size: 16px;
            margin-top: 25px;
            color: #FFFFFF;
        }

        .icons {
            width: 19px;
            height: 18px;
        }
    }

    :deep(.van-cell) {
        padding: 0 !important;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    :deep(.van-field__label) {
        width: 98px !important;
    }

    :deep(.van-field__right-icon) {
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .liveStreamingMechanisms {
        position: absolute;
        top: 0;
        left: 0;
        width: 50px;
        height: 20px;
        background: #0094FF;
        border-radius: 2px 0px 2px 0px;
        font-weight: 400;
        font-size: 12px;
        color: #FFFFFF;
        text-align: center;
        line-height: 20px;
    }

    .conent_pre {
        width: 100%;
        padding: 15px;
        box-sizing: border-box;
        background-color: #fff;
        margin-top: 10px;

        .conent_pre_header {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .conent_pre_img {
                width: 90px;
                height: 90px;

                .van-image {
                    width: 90px;
                    height: 90px;

                    :deep(.van-image__img) {
                        border-radius: 5px !important;
                    }
                }
            }

            .conent_pre_des {
                width: calc(100% - 90px);
                height: 90px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                flex-wrap: wrap;
                padding-left: 10px;
                align-content: space-around;

                .contnt_title {
                    width: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    .contnt_styleName {
                        font-weight: 400;
                        font-size: 14px;
                        color: #1A1B1C;
                        width: 150px;
                        height: 20px;
                        white-space: nowrap;
                        /* 确保文本在一行内显示 */
                        overflow: hidden;
                        /* 隐藏溢出的内容 */
                        text-overflow: ellipsis;
                    }

                    .contnt_status {
                        width: 67px;
                        height: 26px;
                        background: #EBF4FF;
                        border-radius: 2px;
                        font-weight: 400;
                        font-size: 14px;
                        color: #0094FF;
                        text-align: center;
                        line-height: 26px;
                    }

                    .contnt_status1 {
                        width: 67px;
                        height: 26px;
                        background: #EBF4FF;
                        border-radius: 2px;
                        font-weight: 400;
                        font-size: 14px;
                        color: #0094FF;
                        text-align: center;
                        line-height: 26px;
                    }

                    .contnt_status2 {
                        width: 67px;
                        height: 26px;
                        background: #E7FDEE;
                        border-radius: 2px;
                        font-weight: 400;
                        font-size: 14px;
                        color: #19D11B;
                        text-align: center;
                        line-height: 26px;
                    }

                    .contnt_status3 {
                        width: 67px;
                        height: 26px;
                        background: #FDE7E7;
                        border-radius: 2px;
                        font-weight: 400;
                        font-size: 14px;
                        color: #FC2540;
                        text-align: center;
                        line-height: 26px;
                    }

                    .contnt_status4 {
                        width: 67px;
                        height: 26px;
                        background: #EBF4FF;
                        border-radius: 2px;
                        font-weight: 400;
                        font-size: 14px;
                        color: #0094FF;
                        text-align: center;
                        line-height: 26px;
                    }

                }

                .contnt_mechanism {
                    width: 100%;
                    font-weight: 400;
                    font-size: 12px;
                    color: #B8BECA;
                    white-space: nowrap;
                    /* 确保文本在一行内显示 */
                    overflow: hidden;
                    /* 隐藏溢出的内容 */
                    text-overflow: ellipsis;
                }

                .contnt_bottom {
                    width: 100%;
                    height: 20px;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;

                    .price {
                        font-weight: 500;
                        font-size: 14px;
                        color: #FC2540;
                    }

                    .commission {
                        font-weight: 500;
                        font-size: 14px;
                        color: #FC2540;
                    }

                    .coreName {
                        font-weight: 400;
                        font-size: 12px;
                        color: #0094FF;
                    }
                }
            }
        }

        .product_detail_title-content-info {
            margin-top: 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .product_detail_title-content-info-name {
                font-weight: 400;
                font-size: 14px;
                color: #1a1b1c;
                line-height: 14px;
                width: 100px;
            }

            .colors {
                color: #0094FF !important;
            }

            .product_detail_title-content-info-content {
                flex: 1;
                min-width: 0;
                font-weight: 400;
                font-size: 14px;
                color: #b8beca;
                line-height: 14px;
                margin-left: auto;
                display: flex;
                justify-content: flex-end;
                word-break: break-all;
            }

            .contents {
                width: 200px;
                font-weight: 400;
                font-size: 14px;
            }

        }

        .divs {
            margin-top: 20px;
            display: flex;
            align-items: center;
            justify-content: flex-end;
        }

        .buttons {
            width: 67px;
            height: 26px;
            background: #fff;
            border-radius: 2px;
            font-weight: 400;
            font-size: 14px;
            color: #FC2540;
            text-align: center;
            line-height: 26px;
            border: 1px solid #FC2540;
        }
    }

    :deep(.van-overlay) {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    :deep(.van-dialog__content) {
        box-sizing: border-box;
        padding: 20px;
    }

    .dialog_title {
        text-align: center;
        margin: 20px;
    }

    .dialog_buttons {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .cancel {
            width: 135px;
            height: 44px;
            border-radius: 23px;
            border: 1px solid #1A1B1C;
            text-align: center;
            line-height: 44px;
        }

        .save {
            width: 135px;
            height: 44px;
            background: #0094FF;
            border-radius: 23px;
            text-align: center;
            line-height: 44px;
            font-weight: 400;
            font-size: 14px;
            color: #FFFFFF;
        }
    }

}
</style>